package com.googlecode.tapestry5validator.hibernate.validators;

import org.apache.tapestry5.Field;
import org.apache.tapestry5.FieldValidator;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.services.FormSupport;
import org.hibernate.validator.Validator;

public class CommonFieldValidator implements FieldValidator<Object> {

	private final Field field;
	private final FormSupport formSupport;
	private final Validator<?> validator;
	private final String message;
	private final Object constraint;
	private final String jsFunctionName;
	private final boolean required; 
	
	
	public CommonFieldValidator(Field field, 
	                            FormSupport formSupport,
	                            String jsFunctionName,
	                            Validator<?> validator,
	                            String message,
	                            Object constraint,
	                            boolean required) {

		this.field = field;
		this.formSupport = formSupport;
		this.jsFunctionName = jsFunctionName;
		this.validator = validator;
		this.message = message;
		this.constraint = constraint;
		this.required = required;

	}

	@Override
	public boolean isRequired() {
		return required;
	}

	@Override
	public void render(MarkupWriter writer) {
		if (jsFunctionName == null) {
			return;
		}
		formSupport.addValidation(field, 
		                          jsFunctionName,
		                          message, 
		                          constraint);
	}

	@Override
	public void validate(Object value) throws ValidationException {
		if (!validator.isValid(value)) {
			throw new ValidationException(message);
		}
	}

}
